package com.heima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.common.PageResult;
import com.heima.mapper.RegionMapper;
import com.heima.pojo.Node;
import com.heima.pojo.Region;
import com.heima.pojo.dto.PageNodeDto;
import com.heima.pojo.dto.PageRegionDto;
import com.heima.pojo.dto.RegionDto;
import com.heima.pojo.vo.RegionVo;
import com.heima.service.RegionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class RegionServiceImpl implements RegionService {

    @Autowired
    private RegionMapper regionMapper;

    /**
     * 区域搜索
     * @param pageRegionDto
     * @return
     */
    @Override
    public PageResult<RegionVo> searchRegion(PageRegionDto pageRegionDto) {
        PageHelper.startPage(pageRegionDto.getPageIndex(), pageRegionDto.getPageSize());
        Page<RegionVo> list = regionMapper.findByName(pageRegionDto);

    /*    // 将 Long 类型的 id 转 String
        for (RegionVo region : list.getResult()) {
            region.setId(String.valueOf(region.getId())); // 如果 Mapper 返回的是 Long
        }*/

        // 计算总页数
        int totalPage = (int) Math.ceil((double) list.getTotal() / pageRegionDto.getPageSize());
        return new PageResult<>(
                pageRegionDto.getPageIndex(),
                pageRegionDto.getPageSize(),
                totalPage,
                list.getTotal(),
                list.getResult()
        );
    }

    /**
     * 区域新增
     * @param regionDto
     * @return
     */
    @Override
    public Boolean saveRegion(RegionDto regionDto) {
        Region region = new Region();
        BeanUtils.copyProperties(regionDto, region);
        region.setName(regionDto.getRegionName());
        Integer math = regionMapper.insertRegion(region);
        return math > 0;
    }

    /**
     * 修改区域信息
     * @param regionDto
     * @return
     */
    @Override
    public Boolean updateRegion(RegionDto regionDto) {
        Integer count = regionMapper.modifyRegion(regionDto);
        return count > 0;
    }

    /**
     * 删除区域信息
     * @param regionId
     * @return
     */
    @Override
    public Boolean deleteRegion(String regionId) {
        try {
            // 如果区域内的点位数大于0，则不能删除 并抛出异常
            if (regionMapper.queryNodeCount(regionId) > 0) {
                throw new RuntimeException("区域内存在节点，不能删除");
            }
            Long id = Long.parseLong(regionId);
            Integer count = regionMapper.deleteRegion(id);
            return count > 0;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}
